--#SET TERMINATOR @
DROP TRIGGER HarmonogramTrigger@

CREATE TRIGGER HarmonogramTrigger
  BEFORE INSERT ON HarmonogramZajec
  --LANGUAGE SQL
  REFERENCING NEW AS o
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
  	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			Klasy_id = o.Klasy_id
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			Nauczyciele_id = o.Nauczyciele_id
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			sala IS NOT NULL AND sala = o.sala
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
  END
  @
  
  DROP TRIGGER HarmonogramTriggerUpdate@

CREATE TRIGGER HarmonogramTriggerUpdate
  BEFORE Update ON HarmonogramZajec
  --LANGUAGE SQL
  REFERENCING NEW AS o
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
  	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			Klasy_id = o.Klasy_id
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			Nauczyciele_id = o.Nauczyciele_id
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
	IF (SELECT COUNT(*) AS count FROM HarmonogramZajec WHERE 
			sala IS NOT NULL AND sala = o.sala
			AND dzien_tygodnia = o.dzien_tygodnia
			AND (
			  (HarmonogramZajec.start >= o.start AND HarmonogramZajec.start <= HarmonogramZajec.koniec)
			  OR (koniec >= o.start AND koniec <= o.koniec)
			  OR (HarmonogramZajec.start < o.start AND koniec > o.koniec)
			)
	    ) > 0 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
  END
  @

  --#SET TERMINATOR ;